<?php

namespace App\Http\Controllers\Admin\Config;

use App\Http\Requests\Admin\Config\ChannelRequest;
use App\Http\Requests\Admin\Config\ServerRequest;
use App\Models\Config\Channels;
use App\Models\Config\Servers;
use App\Models\Enum\Status;
use App\Services\Config\ChannelsService;
use App\Services\Config\ServersService;

use App\Http\Controllers\Admin\BaseController;
use App\Services\Config\GamesService;
use Illuminate\Http\Request;

class ServersController extends BaseController
{

    public function __construct(GamesService $gamesService, ChannelsService $channelsService, ServersService $serversService)
    {
        $this->channelsService = $channelsService;
        $this->gamesService = $gamesService;
        $this->serversService = $serversService;
    }

    public function index(Request $request)
    {
        $reqGameId = $request->input('game_id');
        $reqChannelId = $request->input('channel_id');
        $reqPageSize = $request->page_size;
        $servers = $this->serversService->getPage($request);

        return view('config.servers.index', compact('servers', 'reqGameId', 'reqPageSize', 'reqChannelId'));
    }

    public function create()
    {
        return view('config.servers.create');
    }

    public function store(ServerRequest $request)
    {
        Servers::create($request->all());

        flash('添加成功')->success()->important();

        return $this->redirect($request);
    }

    public function edit($id)
    {
        $server = $this->serversService->ById($id);
        $reqGameId = $server->game_id;
        $reqChannelId = $server->channel_id;

        return view('config.servers.edit', compact('server', 'reqGameId', 'reqChannelId'));
    }

    public function update(ServerRequest $request, $id)
    {
        $this->serversService->update($request, $id);

        flash('更新成功')->success()->important();

        return $this->redirect($request);
    }

    public function delete($id)
    {
        $server = $this->serversService->ById($id);

        if (empty($server)) {
            flash('删除失败')->error()->important();

            return redirect()->back();
        }

        $server->delete();

        flash('删除成功')->success()->important();

        return redirect()->back();
    }

    public function status($status, $id)
    {
        $server = $this->serversService->ById($id);

        if (empty($server)) {
            flash('操作失败')->error()->important();

            return redirect()->back();
        }

        $server->update(['status' => $status]);

        flash('更新状态成功')->success()->important();

        return redirect()->back();
    }

}
